<template>
	<view class="upload-comp">
		<template v-if="!slots">
			<view class="upload-comp-btn" @click="uploadFileFun">
				<slot name="content"></slot>
				<image src="@/static/images/projectDetail/upload-icon.png" class="upload-icon-img"></image>
				<view class="upload-comp-text">
					上传文件
				</view>
			</view>
			<view class="upload-tip">
				<!-- 支持拓展名：doc、docx -->
				{{uploadInfo.tooltip}}
			</view>
			<image src="@/static/images/projectDetail/upload-icon.png" class="upload-icon-fun-img" @click="uploadFileFun">
			</image>
		</template>
		<view v-else  @click="uploadFileFun">
			<slot></slot>
		</view>
		
		<ToastComp v-if="toastInfo.visible" :toastInfo="toastInfo" @closeToast="closeToast" @canel="cancelFun"
			@cancel="confirmFun"></ToastComp>
	</view>
</template>

<script>
	import OSS from "@/static/OSS/aliyun-oss-sdk-4.4.4.min.js"
	import ToastComp from "@/components/ToastComp/ToastComp.vue"
	import {
		getSTSToken
	} from "@/common/api/project.js"
	import { getNowDate ,dateFormat} from "@/utils/index.js"
	export default {
		props: {
			slots:{
				type:Boolean,
				default:false,
			},
			isFixed:{
				type:Boolean,
				default:false,
			},
			uploadInfo: {
				type: Object,
				default: () => {
					return {
						btnTxt: '上传文件',
						uploadTip: '支持拓展名：doc、docx',
						fileList: [],
						project_id: '',
						topic_id: '',
						file_size_check:0,
						Id: ''

					}
				}
			}
		},
		data() {
			return {
				STSTokenData: '',
				// toast
				toastInfo: {
					visible: false,
					type: 'success',
					title: '',
					subTitle: '',
					cancel: false,
					confirm: false,
					closeShow: true
				},
			}
		},
		watch: {
			uploadInfo: {
				handler() {
					// console.log(this.uploadInfo)
				},
				immediate: true,
				deep: true
			}
		},
		mounted() {
			// this.getSTSTokenFun()
		},
		methods: {
			// 获取ststoken
			getSTSTokenFun() {
				getSTSToken().then(res => {
					if (res.code == 200) {
						
						this.STSTokenData = res.data;
					} else {
						uni.hideToast();
					}
				})
			},
			uploadFileFun() {
				this.getSTSTokenFun()
				const that = this;
				uni.chooseFile({
					count: 1, // 默认100
					// extension: ['.docx', '.doc'],
					success: (res) => {
						console.log(res)
						const tempFilePaths = res.tempFilePaths;
						let file = res.tempFiles[0]
						const type = file.name.substr(file.name.lastIndexOf(".")).toLowerCase();
						const name = file.name.substr(0, file.name.lastIndexOf("."))
						// 上传类型限制
						// const fileType = [".doc", ".docx"];
						// if (!fileType.includes(type)) {
						// 	let typeTxt = fileType.join(",");
						// 	uni.showToast({
						// 		title: `温馨提示：只支持${typeTxt}格式的文件`,
						// 		icon: 'none',
						// 		duration: 2000
						// 	})
						// 	return;
						// }
						// is_check: 1 需要校验文件名需要和题目名称一致
						if (that.uploadInfo.is_check && that.uploadInfo.answer_type === 1) {
							if (that.uploadInfo.topicName !== name) {
								// uni.showToast({
								// 	title: `题目配置：【${that.uploadInfo.title}】上传的文件名需要和题目名称一致！`,
								// 	icon: 'none',
								// 	duration: 2000
								// })
								that.toastInfo.title = '上传失败'
								that.toastInfo.subTitle = '当前上传的文件与题目名称不符。请修改文件名字重新上传，文件名字必须和题目名字一致，否则会失败！'
								that.toastInfo.type = 'error'
								that.toastInfo.closeShow = true
								// this.toastInfo.cancel = true
								that.toastInfo.confirm = true
								that.toastInfo.visible = true
								return
							}
						}
						if(that.uploadInfo.is_check == 1){
							const isLt2M = file.size / 1024 / 1024 <= that.uploadInfo.file_size_check;
							if (!isLt2M) {
								that.toastInfo.title = '上传失败'
								that.toastInfo.subTitle = '文件最大不能超过'+that.uploadInfo.file_size_check+'M！'
								that.toastInfo.type = 'error'
								that.toastInfo.closeShow = true
								that.toastInfo.cancel = true
								that.toastInfo.confirm = true
								that.toastInfo.visible = true
								return;
							}
						}
						
						that.uploadOSSFun(file)
					},


				});
			},
			// 上传oss
			uploadOSSFun(file) {
				uni.showLoading({
					title: `上传中...`,
					mask: true
				})
				// 这里是OSS，需要配置oss
				const client = new OSS.Wrapper({
					// yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
					region: "oss-cn-shanghai",
					// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
					accessKeyId: this.STSTokenData.accessKeyId,
					accessKeySecret: this.STSTokenData.accessKeySecret,
					stsToken: this.STSTokenData.stsToken,
					endpoint:  "https://" + this.STSTokenData.endPoint, // 拼上https防止跨域
					// 填写Bucket名称。
					bucket: this.STSTokenData.bucket,
					secure: true,
					// cname: true
				});
				// 存储的文件路径
				// let projectName = this.uploadInfo.projectName + "（一级文件夹）"
				let timeName = getNowDate()
				let type = file.name.substr(file.name.lastIndexOf("."));
				let name = file.name.substr(0, file.name.lastIndexOf("."))
				// console.log(type, name)
				// console.log(this.uploadInfo)
				// let fileName = ''
				// if (this.uploadInfo.answerTypeVal == 1) {
				// 	fileName = file.name
				// } else if (this.uploadInfo.answerTypeVal == 2) {
				// 	let content = this.uploadInfo.content
				// 	console.log(content)
				// 	let arr = content.split('?')
				// 	console.log(arr)
				// 	let n = file.name.substr(file.name.lastIndexOf("-")+1, file.name.lastIndexOf("."));
				// 	n = Number(n)
				// 	if (n == NaN) {
				// 		n = ''
				// 	}
				// 	if (n > 9 && n <= 99) {
				// 		n = '0' + n 
				// 	}
				// 	if (n <= 9) {
				// 		n = '00' + n 
				// 	}
				// 	let fixNum = n ? '-' + n : ''
				// 	fileName = file.name + fixNum + type
				// 	console.log(fileName)
				// }
				// let path = `task-assign/${projectName}/${timeName}/${fileName}`
				// console.log(path)
				// let storeAs = path
				// let fileName = name + getNowDate('hh:mm:ss') + type
				let fileName = name + type
				let storeAs =
					`${ window.location.href.indexOf('zhaixiaozhi') > -1?'task-assign-project':this.isFixed?'composite-picture' :'test-task-assignment'}/${this.uploadInfo.project_id}/${this.isFixed? dateFormat(new Date(),'yyyyMMddHHmmss')+'/':''}${this.uploadInfo.topic_id}/${timeName}/${fileName}` // task-assign/{projectId}/{topicId}/{topic_configurationId}/filenam
				console.log(storeAs)
				client.multipartUpload(storeAs, file)
					.then(result => {
						uni.hideLoading()
						// console.log("result.res");
						// console.log(result.res);
						let aliUrl = result.res.requestUrls;
						console.log(aliUrl[0]); // 阿里云返回给的url
						let f = {
							name: file.name,
							size: file.size,
							url: aliUrl[0]
						}
						let data = {
							file: f,
							uploadInfo: this.uploadInfo
						}
						// uni.showToast({
						// 	title: `上传成功`,
						// 	icon: 'none',
						// 	duration: 1500
						// })
						this.toastInfo.title = '上传成功'
						this.toastInfo.subTitle = ''
						this.toastInfo.type = 'success'
						this.toastInfo.closeShow = false
						this.toastInfo.cancel = false
						this.toastInfo.confirm = false
						this.toastInfo.visible = true
						setTimeout(()=>{
							this.toastInfo.visible = false
						}, 1500)
						debugger
						this.$emit('getUploadFileList', data)
					})
					.catch((err) => {
						uni.hideLoading()
						console.log(err);
					});
			},
			// tosat
			closeToast() {
				this.toastInfo.visible = false
			},
			// 取消
			cancelFun() {
				this.toastInfo.visible = false
			},
			// 确认
			confirmFun() {
				this.toastInfo.visible = false
			}
		}
	}
</script>

<style lang="scss" scoped>
	.upload-comp {
		.upload-comp-btn {
			cursor: pointer;
			&:active {
				opacity: .6;
			}

			width: 116px;
			height: 36px;
			background: #FFFFFF;
			border-radius: 2px;
			border: 1px solid #E7EAEF;
			font-size: 14px;
			font-family: PingFangSC-Regular,
			PingFang SC;
			font-weight: 400;
			color: #2D3036;
			display: flex;
			align-items: center;
			justify-content: center;

			.upload-icon-img {
				width: 16px;
				height: 16px;
				display: inline-block;
				margin-right: 4px;
			}
		}

		.upload-tip {
			font-size: 12px;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #979EAA;
			margin-top: 8px;
			word-break: break-all;
			line-height: 1.5;
		}

		.upload-icon-fun-img {
			display: none;
		}
	}

	@media screen and (min-width: 0px) and (max-width:1024px) {
		.upload-comp {
			.upload-comp-btn {
				display: none;
			}

			.upload-tip {
				// display: none;
			}

			.upload-icon-fun-img {
				display: block;
				width: 16px;
				height: 16px;
				position: absolute;
				right: 16px;
				top: 0;
			}
		}
	}
</style>
